package org.ielts.service;

import org.apache.commons.lang.StringUtils;
import org.ielts.domain.base.Campus;
import org.ielts.domain.base.Classroom;
import org.ielts.profile.IeltsProfile;
import org.ielts.repository.ClassroomRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yifeng.ProfileContext;
import com.yifeng.profile.Profile;

@Service
public class ClassroomService {

	@Autowired
	ClassroomRepository classroomRepository;

	@Transactional
	public Classroom createClassroom(String name, String campusId) {
		Classroom classroom = new Classroom();
		classroom.setName(name);

		Campus campus = new Campus();
		campus.setId(campusId);

		classroom.setCampus(campus);

		classroomRepository.save(classroom);

		return classroom;
	}

	@Transactional
	public Classroom findClassroomByName(String name) {
		Classroom classroom = classroomRepository.findOneByName(name);
		return classroom;
	}

	@Transactional
	public Iterable<Classroom> findAll() {
		Sort sort = new Sort(new Order("name"));
		String campusId = ((IeltsProfile) Profile.getInstance().getProfile()).getCampus();
		if (StringUtils.isBlank(campusId)) {
			Iterable<Classroom> classrooms = classroomRepository.findAll(sort);
			return classrooms;
		} else {
			Iterable<Classroom> classrooms = classroomRepository.findAllByCampus(campusId);
			return classrooms;
		}
	}

	@Transactional
	public Classroom findOne(String classroomId) {
		Classroom classroom = classroomRepository.findOne(classroomId);

		return classroom;
	}

	@Transactional
	public Classroom modifyClassroom(String id, String name, String campusId) {
		Classroom classroom = classroomRepository.findOne(id);
		classroom.setName(name);

		Campus campus = new Campus();
		campus.setId(campusId);

		classroom.setCampus(campus);

		return classroom;
	}

	@Transactional
	public void removeClassroom(String id) {
		classroomRepository.delete(id);
	}

	@Transactional
	public Classroom findByNameAndCampus(String classroomName, String campus) {
		Classroom classroom = classroomRepository.findByNameAndCampus(classroomName, campus);

		return classroom;
	}
}
